package com.seckill.goods.controller;

import com.seckill.commons.Constants;
import com.seckill.commons.ReturnObject;
import com.seckill.goods.model.Goods;
import com.seckill.goods.service.GoodsService;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;


@Controller
public class GoodsController {
    @Resource
    private GoodsService goodsService;
    @RequestMapping("/")
    public String index(Model model){
        List<Goods>list= goodsService.getGoodsAll();
        model.addAttribute("goodsList",list);
        return "index";
    }
    @RequestMapping("/showGoodsInfo")
    public String showGoodsInfo(Integer goodsId,Model model){
        Goods goods= goodsService.getGoodsById(goodsId);
        model.addAttribute("goods",goods);
        return "goodsInfo";
    }
    @RequestMapping("/getSysTime")
    @ResponseBody
    public Object getSysTime(){
        return new ReturnObject<Long>(Constants.OK,"获取系统时间成功",System.currentTimeMillis());
    }
    @RequestMapping("/getRandomName")
    @ResponseBody
    public Object getRandomName(Integer goodsId){
        Goods goods= goodsService.getGoodsById(goodsId);
        //进入if表示没有获取到商品信息，原因可能是用户手动拼接的请求
        if(goods==null){
            return new ReturnObject<String>(Constants.ERROR,"商品信息异常",null);
        }
        long sysTime=System.currentTimeMillis();
        //进入if表示活动还没有开始，原因可能是用户手动拼接的请求
        if(sysTime<goods.getStartTime().getTime()){
            return new ReturnObject<String>(Constants.ERROR,"活动还没有开始",null);
        }
        //进入if表示活动已经结束开始，原因可能是用户手动拼接的请求
        if(sysTime>goods.getEndTime().getTime()){
            return new ReturnObject<String>(Constants.ERROR,"活动已经结束",null);
        }
        return new ReturnObject<String>(Constants.OK,"获取随机名成功",goods.getRandomName());
    }
    @RequestMapping("/secKill")
    @ResponseBody
    public Object secKill(Integer goodsId, String randomName, BigDecimal price){
        //当前登录用户的Id
        Integer uid=1;
        //调用秒杀业务方法，返回下单结果, 0表示下单成功
        int result=goodsService.secKill(goodsId,randomName,price,uid);
        switch (result){
            case 1:
                return new ReturnObject(Constants.ERROR,"商品信息异常",null);
            case 2:
                return new ReturnObject(Constants.ERROR,"商品已被抢光",null);
            case 3:
                return new ReturnObject(Constants.ERROR,"不能重复下单，请在<我的订单>中查看！",null);
            case 0:
                return new ReturnObject(Constants.OK,"下单成功",null);
            default:
                return new ReturnObject(Constants.ERROR,"下单失败",null);
        }

    }
}
